﻿using System;
using System.Web.UI.WebControls;
using DAL.Repositories;
using GameAdmin.Classes;

namespace GameAdmin.Pages
{
    public partial class questions : System.Web.UI.Page
    {
        #region Page variables (paging)

        private int? _PageIndex;
        private int PageIndex
        {
            get
            {
                if (_PageIndex == null)
                {
                    if (!String.IsNullOrEmpty((string)RouteData.Values["page"])) _PageIndex = Int32.Parse((string)RouteData.Values["page"]);
                    else _PageIndex = 1;
                }
                return (int)_PageIndex;
            }
        }

        private int PagingLimit = 20;

        private int PagingSkip
        {
            get
            {
                return (PageIndex - 1) * PagingLimit + 1;
            }
        }

        private int TotalItems;

        #endregion

        protected void Page_Init(object sender, EventArgs e)
        {
            gw.SelectedIndexChanged += new EventHandler(gw_SelectedIndexChanged);
            gw.RowDeleting += new GridViewDeleteEventHandler(gw_RowDeleting);
            gw.RowEditing += new GridViewEditEventHandler(gw_RowEditing);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetQuestions();
            }
        }

        #region Event handling

        void gw_RowEditing(object sender, GridViewEditEventArgs e)
        {
            Response.Redirect("~/question/" + gw.Rows[e.NewEditIndex].Cells[0].Text, true);
        }

        void gw_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int idToDelete = Int32.Parse(gw.Rows[e.RowIndex].Cells[0].Text);
            QuestionRepository.Delete(idToDelete);

            GetQuestions();
        }

        void gw_SelectedIndexChanged(object sender, EventArgs e)
        {
            Response.Redirect("~/answers/question-" + gw.SelectedRow.Cells[0].Text, true);
        }
  
        #endregion

        private void GetQuestions()
        {
            gw.DataSource = QuestionRepository.GetQuestions(PagingSkip, PagingLimit, out TotalItems);
            gw.DataBind();

            GetPagination();
        }

        private void GetPagination()
        {
            HelperMethods.AddPagination(TotalItems, PagingLimit, PageIndex, "~/questions/", pnlPagination);
        }
    }
}